<?php
/**
 * Created by PhpStorm.
 * UsersF: Mloong
 * Date: 2018/11/30
 * Time: 11:00
 */

namespace app\admin\service;


use app\admin\model\Account;
use app\admin\model\Popularize;
use app\admin\model\Record;
use app\lib\exception\ParameterException;
use Driver\Cache\Redis;
use Page\Page;
use pinyin\Hzpy;
use think\Exception;

class PopularizeService
{
    # 添加账号
    public static function addAccount($data)
    {
        $model = new Account();
        $pinyin = new \pinyin\Hzpy();
        $data['name'] = $pinyin->zhuan($data['name']);
        # 先判断账号是否存在
        $name = $model->where('name','=',$data['name'])
            ->find();
        if($name){
            return [
                'success' => false,
                'msg' => '账号已存在'
            ];
        }else{
            $data['add_time'] = now_time();
            $data['pwd'] = md5($data['password']);
            # 判断数组中是否包含status和repeat
            key_exists('status', $data) ? $data['status'] =1 : $data['status'] = 0;
            key_exists('repeat', $data) ? $data['repeat'] =1 : $data['repeat'] = 0;
            unset($data['password']);

            try{
                $result= $model::create($data);
            }catch (Exception $e){
                return [
                    'success' => false,
                    'msg' => '添加失败,mysql出错'
                ];
            }
            # 获取最新插入的id 同步写入redis-hash
            $id= $result->id;
            # 把添加的账号写入到redis
            self::getAccount($model, $id);
            if($result){
                return [
                    'success' => true,
                    'msg' => '添加成功'
                ];
            }else{
                return [
                    'success' => false,
                    'msg' => '添加失败'
                ];
            }
        }
    }
    # 更新推广账号
    public static function upAccount($data)
    {
        $model = new Account();
        $data['up_time'] = now_time();
        if($data['password'] == ''){
            unset($data['password']);
        }else{
            $data['pwd'] = md5($data['password']);
            unset($data['password']);
        }
        # 判断数组中是否包含status和repeat
        key_exists('status', $data) ? $data['status'] =1 : $data['status'] = 0;
        key_exists('repeat', $data) ? $data['repeat'] =1 : $data['repeat'] = 0;
        try{
            $model::where('id','=',$data['id'])
                ->update($data);
        }catch (Exception $e){
            return [
                'success' => false,
                'msg' => '更新失败'
            ];
        }
        # 先查询出刚刚更新的数据，同步写入redis
        self::getAccount($model, $data['id']);

        return [
            'success' => true,
            'msg' => '更新成功'
        ];

    }
    # 同步写入redis
    private static function getAccount($model, $id)
    {
        $account_data = $model::where('id','=',$id)->find()->toArray();
        $redis_hash_key_account = config('redis.account').$account_data['name'];
        $redis_hash_key_logo = config('redis.logo').$account_data['logo'];
        Redis::hMset($redis_hash_key_account, $account_data);
        Redis::hMset($redis_hash_key_logo, $account_data);
    }

    # 查找所有的推广账号
    public static function getAll($page,$limit)
    {
        $model = new Account();
        $all =  $model->hidden(['pwd'])
            ->page($page,$limit)
            ->select();
        $count = $model->count();
        return array($all,$count);
    }

    # 查找推广账号
    public static function findAccount($data)
    {
        $page = $data['page'];
        $limit = $data['limit'];
        $map = self::findMap($data);
        $model = new Account();
        $list =  $model->where($map);
        $count = $list->count();
        $data = $list->page($page,$limit)
            ->select();
        return array($count,$data);
    }

    # 组装查询条件的数组
    private static function findMap($data)
    {
        $map = array();
        # 先把数组中value为空的值unset 再把所有条件拼接成数组
        # 分页参数page和limit则组成另一个数组
        $file = $data['field'];
        if($file['status'] == 0){
            array_push($map,['status','=',$file['status']]);
        }
        if($file['company_name']){
            array_push($map,['company_name','like','%'.$file['company_name'].'%']);
        }
        return $map;
    }

    public function findAllPopularizeWhere($post,$model_str)
    {
        $this->checkFindData($post['field']);
        $classModel = 'app\\admin\\model\\'.$model_str;
        $model = new $classModel;
        $arr = $this->SpliceWhereArrByPopularize($post);
        $page = new Page($model,$arr['page'],$arr['limit'],[],['add_time' => 'desc'],$arr['where']);
        $result = $page->layuiPage();
        return $result;
    }
    # 组装查询条件
    private function SpliceWhereArrByPopularize($post)
    {
        $page = $post['page'];
        $limit = $post['limit'];

        $filed = $post['field'];
        $time = $filed['time'];
        if(!strstr($time,'.')){
            $time_start = '';
            $time_end = '';
        }else {
            $date = explode('.', $filed['time']);
            $time_start = $date[0];
            $time_end = $date[1];
        }
        $pinyin = new Hzpy();
        $str = $pinyin->zhuan($filed['from']);

        # 所有的字段
        $data = ['from','ip','from','signData','phone','type','first'];
        # 如果字段不存在则添加字段并设置值为空
        foreach ($data as $value){
            if(array_key_exists($value, $filed) == false){
                $filed[$value] = '';
            }
        }

        $arr = [
            'address' => ['address','like','%'.$filed['address'].'%'],
            'ip' => ['ip','like','%'.$filed['ip'].'%'],
            'from' => ['from','=',$str],
            'signData' => ['sign','=',$filed['signData']],
            'time' => ['add_time', 'between time', [$time_start, $time_end]],
            'phone'=> ['phone', '=', $filed['phone']],
            'type'=> ['type', '=', $filed['type']],
            'first'=> ['first', '=', $filed['first']],
        ];

        # 组装where查询条件数组
        $where = [];
        foreach ($filed as $key => $value){
            if($value == ''){
                unset($arr[$key]);
                continue;
            }
            array_push($where,$arr[$key]);
        }

        return [
            'page' => $page,
            'limit' => $limit,
            'where' => $where
        ];
    }
    # 校验参数是否合法
    private function checkFindData($data)
    {
        $arr = ['from','address','ip','time','signData','type', 'phone', 'first'];
        foreach ($data as $key=>$value){
            if(in_array($key,$arr) == false){
                throw new ParameterException([
                   'msg' => '参数不合法'
                ]);
            }
        }
        return;
    }
    # 检查参数是否合法
    public function findAllSign($company)
    {
        $pinyin = new \pinyin\Hzpy();
        $from = $pinyin->zhuan($company);
        $model = new Account();
        $result = $model->where('name','=',$from)
            ->find();
        if(!$result){
            throw new ParameterException([
               'msg' => '推广方不存在'
            ]);
        }else{
            $sign_str = ($result->toArray())['sign'];
            $sign_arr = explode('%',$sign_str);
        }
        return $sign_arr;
    }
}